﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using Pavilion.DesignerTool.NodeDesignerTool.ImplementationsForConnectableListbox;
using System.Collections.ObjectModel;

namespace Pavilion.DesignerTool.ViewTools.ConnectableListBox
{
    public class LinkWrapper : IConnectonator
    {
        public event Action<LinkWrapper> Disposed;

        public Link Link { get; private set; }
        public ObservableCollection<LockWrapper> LockWrapperCollection { get; set; }
        public IConnectableItem Start { get; set; }
        public IConnectableItem End { get; set; }

        public FrameworkElement StartLBI { get; set; }
        public FrameworkElement EndLBI { get; set; }

        public LinkWrapper(Link link, IConnectableItem start, IConnectableItem end)
        {           
            this.Link = link;
            this.Start = start;
            this.End = end;
            LockWrapperCollection = new ObservableCollection<LockWrapper>();

            foreach (var Lock in this.Link.LockCollection)
                LockWrapperCollection.Add(new LockWrapper(Lock));

            Link.Disposed += (sender, e) => Dispose();
        }

        public void Dispose()
        {
            Link = null;
            Start = null;
            End = null;
            LockWrapperCollection.Clear();
            OnDisposed();
            Disposed = null;
        }

        internal void AddLockWrapper(LockWrapper lockWrapper)
        {
            LockWrapperCollection.Add(lockWrapper);
            Link.AddLock(lockWrapper.Lock);
        }

        internal void RemoveLockWrapper(LockWrapper lockWrapper)
        {
            this.LockWrapperCollection.Remove(lockWrapper);
            Link.RemoveLock(lockWrapper.Lock);
        }

        internal void RemoveLock(ILock lockItem)
        {
            foreach (LockWrapper lockWrapper in LockWrapperCollection)
            {
                if (lockWrapper.Lock == lockItem)
                {
                    RemoveLockWrapper(lockWrapper);
                    return;
                }
            }
        }

        private void OnDisposed()
        {
            if (Disposed != null)
                Disposed(this);
        }
    }
}
